import { BookedService } from './booked.service';
import { Injectable } from '@angular/core';
import { EventService, EventMessage, EventSource } from '../services/event.service'
import { RequestReplyService } from '../services/request-reply.service'
import { OrtcService, XMPPMessage} from '../services/ortc.service'

import { User, AuthUser } from '../entity/TT';
import { Type, Message, TextMessage } from '../entity/Chat'
import { CONNECTION_STATUS } from '../entity/ORTC';
import { NGXLogger } from 'ngx-logger';

@Injectable({
  providedIn: 'root'
})
export class ChatService {
  private isInited: boolean = false;

  constructor(
    private log: NGXLogger,
    private bookedService:BookedService,
    private eventService: EventService,
    private requestService: RequestReplyService,
    private rtcservice: OrtcService) { }


  init(user: User) {
    this.log.debug("chat init...", this.isInited)
    if(this.isInited){
      console.warn("isInited!")
      return;
    }
    if (!user) {
      this.log.debug("user is invalid!")
      return
    }
    try{
      this.isInited = true;

      this.requestService.GetPassword().subscribe((pwd) => {
        if (!pwd) {
          this.log.debug("pwd is invalid!")
          return
        }
        //初始化jitsi
        this.rtcservice.init(AuthUser.from(user, pwd));
      })

      let emit = this.eventService.emit;
      emit.subscribe((evt: EventMessage) => {

        switch (evt.source) {
          case EventSource.XMPP_MESSAGE:
            let msg: XMPPMessage = evt.data;
            let m = this.transformMessage(msg);
            this.eventService.sendMessage(m);
            break;

          case EventSource.XMPP_CONNECTION_STATUS:
            const status: CONNECTION_STATUS = evt.data;
            if (status === CONNECTION_STATUS.ESTABLISHED) {
              // 获取当前conference
              this.requestService.GetConference().subscribe((jid: string) => {
                if (jid) {
                  this.rtcservice.joinConference(jid);
                  this.bookedService.refresh();
                } else {
                  this.requestService.ListConference().subscribe((list) => {
                    this.eventService.sendConferenceList(list);
                  });
                }
              })
            }
            break;
        }
      })
    }catch(e){
      this.isInited = false;
      this.log.error("init ", e)
    }



  }

  destory(){
    this.log.debug("destory ...")
  }

  transformMessage(xmpp: XMPPMessage): TextMessage {

    let uin = this.getUinFromMsgId(xmpp.id);

    let msg: TextMessage = {
      id: xmpp.id,
      time: xmpp.ts,
      avatar: { url: '', uin: uin, name: '' },
      text: xmpp.text,
    }

    return msg;
  }

  getUinFromMsgId(msgId: string) {
    // g0000000001-9682dc
    return msgId.split("-")[0]
  }

  // getMessageList(bookedId: number): Observable<object[]> {

  //   this.log.debug('getMessageList', bookedId)

  //   // return this.requestService.GetReply(this.listMessageUrl, { bookedId }).pipe(
  //   //   map(reply => {
  //   //     if (reply.success) {
  //   //       return reply.data;
  //   //     }
  //   //     else
  //   //       this.log.debug("error", reply.data);
  //   //   })
  //   // )
  // }


  sendMessage(text: string): boolean {
    return this.rtcservice.sendText(text);
  }

}
